package gw.com.android.ui.onlive;

import android.annotation.SuppressLint;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.EditText;


/**
 * 带有最大字数限制的EditText
 */
@SuppressLint("AppCompatCustomView")
public class EditTextWithMaxLimit extends EditText {

    public EditTextWithMaxLimit(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public int getMax() {
        return max;
    }

    public void setMax(int max) {
        this.max = max;
    }

    private int max = 10;

    private void init() {
        addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {//这个方法并不能应对粘贴进来的内容
            }

            @Override
            public void afterTextChanged(Editable s) {//但是它可以
                int len = s.length();
                if (null != textWatcherCallback)
                    textWatcherCallback.onDataChange(len);
                if (len > max) {// 每一次编辑之后，都自动检查超出了多少个字符，然后把它们删除
                    s.replace(max, len, "");
                }
            }
        });
    }


    public interface TextWatcherCallback {
        void onDataChange(int current);//把当前字数反馈出去
    }

    private TextWatcherCallback textWatcherCallback;

    public void setTextWatcherCallback(TextWatcherCallback textWatcherCallback) {
        this.textWatcherCallback = textWatcherCallback;
    }
}
